package com.ts.api.meta;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Configuration;

/**
 *  元数据上报工厂
 *
 *  @author Pan
 */
@Configuration
@Slf4j
public class MetaReportFactory {

    private RedissonClient redisson;

    public MetaReportFactory(RedissonClient redisson) {
        this.redisson = redisson;
    }

    /**
     *  元数据上报方法
     *
     *  @param metaName 元数据名称，只可唯一
     *  @param metaTask 执行任务
     */
    public void report(String metaName, Runnable metaTask) {
        RLock lock = redisson.getLock(metaName);
        try {
            log.info("启动上报任务-[启动中]-任务名称:{}", metaName);
            if (lock.tryLock()) {
                metaTask.run();
                log.info("启动上报任务-[完成]-任务名称:{}", metaName);
            } else {
                log.info("启动上报任务-[获取锁失败]-任务名称:{}", metaName);
            }
        } catch (Exception e) {
            log.info("启动上报任务-[异常]-任务名称:{}, {}", e.getMessage(), e);
            throw e;
        } finally {
            lock.unlock();
        }
    }
}
